package com.springboot.codeminestarter.codemine.aop.time;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class MethodCostTimeWrapper {
    public static final Logger LOGGER = LoggerFactory.getLogger(MethodCostTimeWrapper.class);

    @Pointcut(value = "execution(* com.springboot.codeminestarter..dao.*.*(..))")
    public void methodCostTimePointCut() {

    }

    @Around("methodCostTimePointCut()")
    public Object handleMethodCost(ProceedingJoinPoint point) throws Exception {

        return handle(point);
    }

    private Object handle(ProceedingJoinPoint point) throws Exception {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        String typeName = signature.getDeclaringTypeName();
        String clazz = typeName.substring(typeName.lastIndexOf(".") + 1);

        Object obj;
        try {
            long entranceTime = System.currentTimeMillis();
            obj = point.proceed();
            long costTime = System.currentTimeMillis() - entranceTime;
            LOGGER.info(">>>>>>> Clazz=[{}], Method=[{}] Cost Time: {}ms", clazz, method.getName(), costTime);
        } catch (Throwable e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return obj;
    }
}
